package com.sparkflow.mysqlbinlog.clickhousesync.service.metadata;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sparkflow.mysqlbinlog.clickhousesync.config.properties.MysqlBinlogProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.Map;

@Component
/**
 * 表元数据服务类
 * 负责初始化和管理表结构元数据信息
 *
 * @author Mr_xiaoZH
 * @date 2025-07-23
 */
public class TableMetadataService {

    @Autowired
    private JdbcTemplate mysqlJdbcTemplate;
    @Autowired
    private MysqlBinlogProperties mysqlBinlogProperties;

    public static TableMetadataCache tableMetadataCache = new TableMetadataCache();

    public void initialize() {
        List<String> tableNames = this.mysqlBinlogProperties.getSyncTables();
        String placeholders = String.join(",", Collections.nCopies(tableNames.size(), "?"));
        String sql = "SELECT TABLE_SCHEMA, TABLE_NAME " +
                "FROM INFORMATION_SCHEMA.TABLES " +
                "WHERE CONCAT(TABLE_SCHEMA, '.', TABLE_NAME) IN (" + placeholders + ")";
        // 执行查询
        List<Map<String, Object>> tables = mysqlJdbcTemplate.queryForList(sql, tableNames.toArray());
        for (Map<String, Object> table : tables) {
            String tableSchema = (String) table.get("TABLE_SCHEMA");
            String tableName = (String) table.get("TABLE_NAME");
            List<Map<String, Object>> columnInfos = mysqlJdbcTemplate.queryForList(
                    "SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", tableName, tableSchema
            );
            List<String> columns = Lists.newArrayList();
            Map<String, String> columnTypeMap = Maps.newHashMap();
            for(Map<String, Object> columnInfo : columnInfos){
                String columnName = (String) columnInfo.get("COLUMN_NAME");
                String dataType = (String) columnInfo.get("DATA_TYPE");
                columns.add(columnName);
                columnTypeMap.put(columnName, dataType);
            }
            List<String> primaryKeys = mysqlJdbcTemplate.queryForList(
                    "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ? AND CONSTRAINT_NAME = 'PRIMARY'",
                    String.class, tableName, tableSchema
            );
            if(primaryKeys == null || primaryKeys.isEmpty()){
                continue;
            }
            String primaryKey = primaryKeys == null || primaryKeys.isEmpty() ? "" : primaryKeys.get(0);
            tableMetadataCache.addTableMetadata(String.format("%s.%s", tableSchema, tableName), columnInfos, columns, primaryKey, columnTypeMap);
        }
    }
}
